<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
use App\Novel;
use App\Shelf;
use DB;

class ShelfController extends Controller
{
    public function addtoshelf($nid){                  //添加小说到书架
    	$shelf = new Shelf(); //新建一个收藏对象
    	$user = Auth::user(); //新建一个user对象，获取登录用户的信息
    	$novel = Novel::find($nid);

    	$cha = Shelf::where(['nid'=>$nid, 'uid'=>$user->uid])->get();
    	if ($cha->isEmpty()) {//当小说不在书架时加入
    		$shelf->uid = $user->uid;
	    	$shelf->nid = $nid; 
	    	$shelf->save();
	    	$novel->collection++;   //小说收藏数量加一
	    	$novel->save();
    	}
    	return redirect("homepage/$nid");
    }

    public function showshelf(){                    //展示书架
    	$user = Auth::user();
    	$novels = DB::table('novels')               //连表查询
    			->join('shelfs', 'shelfs.nid', '=', 'novels.nid')
    			->select('novels.*','shelfs.sid')
    			->where('shelfs.uid', $user->uid)->get();
    	return view('user/shelf',['novels'=>$novels]);
    }

    public function remove($sid){
    	$shelf = Shelf::find($sid);
        $novel = Novel::find($shelf->nid); //找到这本小说，用于更新收藏数量

        $novel->collection--;     //这本小说的收藏数量减一
        $novel->save();
        $shelf->delete();
        return redirect('shelf');
    }
}
